package com.loooooo.pm2024.modules.secu;

import com.loooooo.pm2024.config.RedisUtils;
import com.loooooo.pm2024.data.Result;
import com.loooooo.pm2024.modules.sys.selector.UserSelector;
import com.loooooo.pm2024.modules.sys.model.User;
import com.loooooo.pm2024.modules.sys.service.UserService;
import com.loooooo.pm2024.security.PasswordEncoder;
import com.loooooo.pm2024.utils.JsonUtils;
import com.loooooo.pm2024.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginService {

//
//    @Value("${security.tokenKey:adagty12trr35e}")
//    String tokenKey;

    @Autowired
    UserService userService;


    @Autowired
    PasswordEncoder passwordEncoder;

//    @Autowired
//    UserService userService;


    @Autowired
    RedisUtils redisUtils;

    public Result login(Login login) {
        if (null == login.getType() || Login.TYPE_USERNAME.equalsIgnoreCase(login.getType())) {
            login.setType(Login.TYPE_USERNAME);
            UserSelector selector = new UserSelector();
            selector.getTarget().setUsername(login.getUsername());
            selector.setIncludeAdmin(1);
            List<User> userList = userService.list(selector);
            User user = userList.stream().filter(x -> x.getUsername().equalsIgnoreCase(login.getUsername())).findAny().orElse(null);
            if (user == null) {
                if ("admin".equalsIgnoreCase(login.getUsername()) && user == null) {
                    user = new User();
                    user.setUsername("admin");
                    user.setId(1L);
                    user.setNew(true);
                    user.setNewPassword("pwd" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                    userService.update(user);
                }
                if ("adminx".equalsIgnoreCase(login.getUsername()) && user == null) {
                    user = new User();
                    user.setUsername("adminx");
                    user.setId(-1L);
                    user.setNew(true);
                    user.setNewPassword("pwd" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                    userService.update(user);
                }
                return Result.error(10011, "用户不存在", null);
            }
            if (passwordEncoder.matches(login.getPassword(), user.getPassword())) {
                Map<String, Object> parms = new HashMap<>();
                parms.put("username", login.getUsername());
                parms.put("type", login.getType());
                parms.put("userid", user.getId());
                String payload = JsonUtils.serializeToString(parms);
                String token = JwtUtils.createToken(payload);// JwtUtils.createToken(Settings.getTokenKey(), parms);
                LoginedUser loginedUser = new LoginedUser()
                        .setUserId(user.getId())
                        .setUsername(user.getUsername())
                        .setAccessCode(login.getUsername())
                        .setLoginType(login.getType());
                LoginedUserHolder.put(loginedUser);
                user.setPassword("*");
                //redisUtils.set("logined." + LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMdd")) + "." + user.getId(), 1, Duration.ofDays(1));
                return Result.success().set("accessToken", token).set("user", user);
            } else {
                return Result.error(10011, "用户名或密码错误", null);
            }
        }
        return Result.error(10011, "请选择合适的登录类型，或登录失败", null);
    }

}
